<template>
  <div class="goods">
    <div class="header clearfix">
      <ul class="list fl clearfix">
        <li class="fl list-title">商品名称</li>
        <li class="fl list-input">
          <input type="text" class="form-control" v-model="searchInfo.name" />
        </li>
      </ul>
      <ul class="list fl clearfix">
        <li class="fl list-title">商品类型</li>
        <li class="fl list-input">
          <select class="form-control" v-model="searchInfo.type">
            <option
              :value="item.typeId"
              v-for="(item, index) in proTypeList"
              :key="index"
            >{{item.type}}</option>
          </select>
        </li>
      </ul>
      <ul class="list fl clearfix">
        <li class="fl list-title">商品状态</li>
        <li class="fl list-input">
          <select class="form-control" v-model="searchInfo.status">
            <option value="default">请选择</option>
            <option value="1">正常</option>
            <option value="0">禁用</option>
          </select>
        </li>
      </ul>
      <ul class="list fl clearfix time">
        <li class="fl list-title">添加日期</li>
        <li class="fl list-input">
          <input type="date" class="form-control" v-model="searchInfo.date" />
        </li>
      </ul>
      <ul class="list fl clearfix">
        <li>
          <button class="btn btn-primary" @click="search">搜索</button>
        </li>
      </ul>
    </div>
    <div class="btn-box">
      <button class="btn btn-warning" @click="goGoodsCtPage(2)">添加商品</button>
    </div>
    <div class="content">
      <table class="table table-striped table-hover">
        <thead>
          <tr>
            <th>序号</th>
            <th>商品名称</th>
            <th>商品类型</th>
            <th>商品状态</th>
            <th>添加时间</th>
            <th>更新时间</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in productList" :key="index">
            <td>{{index + 1}}</td>
            <td>{{item.name}}</td>
            <td>{{item.type}}</td>
            <td>{{item.status == 1 ? '上架' : '下架'}}</td>
            <td>{{item.created_at}}</td>
            <td>{{item.updated_at}}</td>
            <td>
              <button class="btn btn-success btn-sm pro-btn" @click=goGoodsCtPage(1,item.pid)>查看</button>
              <button class="btn btn-info btn-sm pro-btn" @click="goGoodsCtPage(3,item.pid)">编辑</button>
              <button
                class="btn btn-warning btn-sm pro-btn"
                v-if="item.status == 0"
                @click="toggleProductStatus(1, item.pid, index)"
              >上架</button>
              <button
                class="btn btn-secondary btn-sm pro-btn"
                v-else
                @click="toggleProductStatus(0, item.pid, index)"
              >下架</button>
              <button class="btn btn-danger btn-sm" @click="remove(item.pid,index)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <nav>
        <ul class="pagination justify-content-center">
          <li class="page-item" :class="{disabled: currentPage == 1}" @click="togglePage()">
            <a class="page-link" href="javascript:void(0);">上一页</a>
          </li>
          <li class="page-item">
            <a class="page-link" href="javascript:void(0);">{{currentPage}}</a>
          </li>
          <li
            class="page-item"
            :class="{disabled: currentPage == totalPage}"
            @click="togglePage(true)"
          >
            <a class="page-link" href="javascript:void(0);">下一页</a>
          </li>
          <li>
            <a class="page-link" href="javascript:void(0);">共 {{totalPage}} 页</a>
          </li>
        </ul>
      </nav>
    </div>
    <Toast></Toast>
  </div>
</template>

<script>
//导入公共方法文件
import { tool } from "../assets/js/tool.js";

//导入消息提示组件
import Toast from "../components/Toast.vue";

export default {
  name: "Goods",

  components: {
    Toast
  },

  data() {
    return {
      //搜索条件
      searchInfo: {
        name: "",
        type: "default",
        status: "default",
        date: ""
      },

      //商品类型
      proTypeList: [],

      //商品列表数据
      productList: [],

      //当前页数
      currentPage: 1,

      //每页显示10条数据
      pageCount: 10,

      //总页数
      totalPage: 0,

      //搜索标记
      isSearch: false
    };
  },
  created() {
    //获取商品类型
    this.getProType();

    //获取商品列表
    this.getProductList();

    //获取数据表的数据数量
    this.getProductDataRows();
  },
  methods: {
    //查看：1、添加：2、编辑：3
    goGoodsCtPage(id,pid) {
      let params = {
        id,
      }
      if(pid){
        params.pid = pid;
      }
      console.log(id,pid);

      this.$router.push({ name: "GoodsDesc", params});
    },

    //获取商品类型
    getProType() {
      this.axios({
        method: "GET",
        url: "/proType"
      })
        .then(result => {
          // console.log('result ==> ', result);
          if (result.data.code == 1052) {
            result.data.result.unshift({
              typeId: "default",
              type: "请选择"
            });
            this.proTypeList = result.data.result;
          }
        })
        .catch(err => {
          console.log("err ==> ", err);
        });
    },

    //获取商品列表信息
    getProductList() {
      //搜索条件
      let condition = this.getSearchCondition();

      //偏移数据量
      condition.offset = (this.currentPage - 1) * this.pageCount;

      //查询数据量
      condition.limit = this.pageCount;

      console.log("condition ==> ", condition);

      //发起请求
      this.axios({
        method: "GET",
        url: "/productList",
        params: condition
      })
        .then(result => {
          console.log("result ==> ", result);

          if (result.data.code == 1080) {
            result.data.result.forEach(v => {
              v.created_at = tool.formatDate(
                new Date(v.created_at),
                "yyyy-MM-dd hh:mm:ss"
              );
              v.updated_at = tool.formatDate(
                new Date(v.updated_at),
                "yyyy-MM-dd hh:mm:ss"
              );
            });

            this.productList = result.data.result;
          }
        })
        .catch(err => {
          console.log("err ==> ", err);
        });
    },

    //点击上下页
    togglePage(isNext) {
      //下一页
      if (isNext) {
        if (this.currentPage < this.totalPage) {
          this.currentPage++;

          console.log(this.currentPage);

          if (this.isSearch) {
            // this.searchType();
          } else {
            this.getProductList();
          }
        }
      } else {
        //上一页
        if (this.currentPage > 1) {
          this.currentPage--;
          if (this.isSearch) {
            // this.searchType();
          } else {
            this.getProductList();
          }
        }
      }
    },

    //搜索
    search() {
      console.log("search");

      this.currentPage = 1;
      this.totalPage = 1;
      //分页
      this.getProductDataRows();

      //获取商品列表记录
      this.getProductList();
    },

    //获取搜索条件
    getSearchCondition() {
      //获取搜索条件
      let searchCondition = this.searchInfo;
      console.log("searchCondition ==> ", searchCondition);

      //过滤条件
      //商品名称 、 日期不能为空
      //商品类型 、 商品不能为default
      let condition = {};

      if (searchCondition.name != "") {
        condition.name = searchCondition.name;
      }

      if (searchCondition.date != "") {
        condition.date = searchCondition.date;
      }

      if (searchCondition.type != "default") {
        condition.type = searchCondition.type;
      }

      if (searchCondition.status != "default") {
        condition.status = searchCondition.status;
      }

      return condition;
    },

    //禁用和启用
    toggleProductStatus(status, pid, index) {
      this.axios({
        method: "POST",
        url: "/productStatus",
        data: {
          status,
          pid
        }
      })
        .then(result => {
          console.log("result ==> ", result);
          if (result.data.code == 1090) {
            this.productList[index].status = status;

            // 成功提示
            this.$showToast({
              message: result.data.msg
            });
          } else if (result.data.code == 1091) {
            this.$showToast({
              message: result.data.msg
            });
          }
        })
        .catch(err => {
          console.log("err ==> ", err);
        });
    },

    //获取商品数据表的数据数量, 用于分页
    getProductDataRows() {
      //搜索条件
      let condition = this.getSearchCondition();

      this.axios({
        method: "GET",
        url: "/productRows",
        params: condition
      })
        .then(result => {
          console.log("result.... ==> ", result);
          //分页
          this.totalPage = Math.ceil(result.data.result / this.pageCount);
        })
        .catch(err => {
          console.log("err ==> ", err);
        });
    },

    //删除商品
    remove(pid, index) {
      this.axios({
        method: "POST",
        url: "/removeProduct",
        data: {
          pid: pid
        }
      })
        .then(result => {
          console.log(result);

          //删除成功
          if (result.data.code == 1074 && result.data.result == 1) {
            //如果存在下一页数据，则补全当前页数据
            //判断是否存在下一页
            if (this.currentPage < this.totalPage) {
              this.getProductList();
              this.getProductDataRows();
            } else {
              //如果是最后一页，存在两种可能
              //1、删除后，最后一页仍然存在数据，则只是删除当前数组数据，不换页码
              if (this.productList.length >= 2) {
                console.log('delectIndex ==> ',index);
                this.productList.splice(index, 1);
                console.log('最后一页有数据',this.productList);
                
              } else {
                console.log('最后一页无数据');
                
                //2、删除后，最后一页不存在数据，判断是否存在上一页数据，如果存在上一页数据，则跳到上一页，否则隐藏分页控件
                //判断是否存在上一页数据
                if (this.currentPage > 1) {
                  console.log('最后一页无数据,但有前一页');
                  
                  this.currentPage--;
                  this.getProductList();
                  this.getProductDataRows();
                } else {
                  console.log('最后一页无数据,且只剩一页');
                  this.productList.splice(index, 1);
                }
              }
            }
          }
          // if(result)
        })
        .catch(err => {
          console.log(err);
        });
    },

  }
};
</script>

<style lang="less" scoped>
.goods {
  //   padding: 20px;
  padding-right: 0px;
}
.list.time {
  margin: 0px;
}
.header {
  .list {
    line-height: 38px;
    margin-right: 20px;
  }
  .list-title {
    width: 80px;
  }
  .list-input {
    width: 200px;
  }
}

.btn-box {
  margin-top: 20px;
}

.content {
  margin-top: 20px;
}
.pro-btn {
  margin-right: 10px;
}
</style>